package com.syl.upimg.utils;

import org.apache.commons.codec.binary.Base64;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author syl
 * @create 2020-04-21 15:56
 **/
public class ImageUtils {

    /**
     * 把图片转换为base64编码
     * @param imagePath
     * @return
     */
    public static String imageToBase64(String imagePath){
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imagePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.encodeBase64String(data);
    }

    /**
     * 把图片转换为data64格式
     * @param imagePath     
     */
    public static String imageToDataBase64(String imagePath) {
        StringBuilder sb = new StringBuilder();
        sb.append("data:");
        sb.append(MimeTypeUtils.getType(imagePath));
        sb.append(";base64,");
        sb.append(imageToBase64(imagePath));
        return sb.toString();
    }

}
